<template>
  <div>
    <TopHeader :local-city-data="localCityData">
      <!-- 将加号按钮插入到 TopHeader 组件的插槽中 -->
      <div class="fixed-button-container">
        <button class="add-button" @click="storeCity">
          <span class="iconfont icon-jia"></span>
        </button>
      </div>
    </TopHeader>

    <div class="container">
      <div v-if="weatherInfo" class="weather-info">
        <h3>你正在预览{{ weatherInfo.city }}的天气信息</h3>
        <p>当日气温: {{ weatherInfo.temperature }}°C</p>
        <p>当日天气: {{ weatherInfo.weather }}</p>
        <p>当日风向: {{ weatherInfo.windDirection }}</p>
        <p>当日风力: {{ weatherInfo.windPower }}级</p>
      </div>
      <div v-else>
        <p>暂无天气数据</p>
      </div>
      <EchartsModel :local-city-data="localCityData" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { getAdCodeData, getWeatherData } from "@/api/index.js";
import EchartsModel from "@/components/EchartsModel.vue";
import TopHeader from "../components/TopHeader.vue";

const router = useRouter();
const route = useRoute();
const localCityData = ref({});
const weatherInfo = ref(null);

onMounted(async () => {
  const cityName = route.params.cityName;
  if (cityName) {
    try {
      const adcodeData = await getAdCodeData(cityName);
      const adcode = adcodeData.geocodes[0].adcode;
      const weatherData = await getWeatherData(adcode);
      localCityData.value = weatherData;

      weatherInfo.value = {
        city: weatherData.forecasts[0].city,
        temperature: weatherData.forecasts[0].casts[0].daytemp,
        weather: weatherData.forecasts[0].casts[0].dayweather,
        windDirection: weatherData.forecasts[0].casts[0].daywind,
        windPower: weatherData.forecasts[0].casts[0].daypower,
      };
    } catch (error) {
      console.error("获取天气数据时发生错误:", error);
    }
  }
});

const storeCity = () => {
  if (weatherInfo.value && weatherInfo.value.city) {
    const storedCities = JSON.parse(localStorage.getItem("cities")) || [];
    if (!storedCities.includes(weatherInfo.value.city)) {
      storedCities.push(weatherInfo.value.city);
      localStorage.setItem("cities", JSON.stringify(storedCities));
      alert(`${weatherInfo.value.city} 成功保存`);
    } else {
      alert(`${weatherInfo.value.city} 已存在`);
    }
  } else {
    alert("无法保存城市名！");
  }
};
</script>

<style lang="scss" scoped>
.fixed-button-container {
  z-index: 200;

  .icon-jia {
    color: #fff;
    background-color: #00668a;
    border: 0;
    cursor: pointer;
    .add-icon {
      width: 30px;
      height: 30px;
    }
  }
}

.container {
  height: calc(100vh - 80px);
  padding: 0 10%;
  background-color: #00668a;
}

.weather-info {
  padding: 20px 0;
  text-align: center;
  color: #fff;
  line-height: 40px;
}
</style>
